from ApplicationCommand import ApplicationCommand

from pyrfid.asn1.Encoder import Encoder
from pyrfid.asn1.Decoder import Decoder


class InventoryTagsCommand(ApplicationCommand):
    """docstring for InventoryTagsCommand"""
    
    def __init__(self, AFI, identifyMethod, numberOfTag):
        self.cmd = '28FC597E03'
        self.rsp = '28FC597F03'
        self.identifyMethod = identifyMethod
        self.numberOfTag = numberOfTag
        self.numOfTagsFound = 0
        self.tagIDs = []
        self.AFI = AFI
        self.listCmdAndData = []
        self.ENCODED_COMMAND = ''
        
    def encode(self):
        
        encoder = Encoder()
        self.listCmdAndData.append(['06', '05', self.cmd])
        self.listCmdAndData.append(['30', '', ''])
        self.listCmdAndData.append(['30', '06', ''])
        self.listCmdAndData.append(['02', '01', encoder.intEncode(self.AFI.APPLICATION_FAMILY)])
        self.listCmdAndData.append(['02', '01', encoder.intEncode(self.AFI.APPLICATION_SUB_FAMILY)])
        self.listCmdAndData.append(['02', '01', encoder.intEncode(self.identifyMethod)])
        numOfTagsHex = encoder.intEncode(self.numberOfTag)
        lenNumOfTagsHex = encoder.lengthEncode(len(numOfTagsHex) / 2)
        self.listCmdAndData.append(['02', lenNumOfTagsHex, numOfTagsHex])
        lenData = len(lenNumOfTagsHex)/2 + len(numOfTagsHex)/2 + 12
        self.listCmdAndData[1][1] = encoder.lengthEncode(lenData)
        self._convertToHexString()
        return self.ENCODED_COMMAND

    def decode(self, encodedRSP):
        if encodedRSP[4:14] != self.rsp:
            raise 'ResponseTypeError'
        
        decoder = Decoder(encodedRSP[16:])
        lenData = decoder.lengthDecode()[0]
        
        # if lenData != len(decoder.data) / 2:
        #             raise 'LengthError'
        #         
        decoder.popData(4)
        self.completionCode = decoder.intDecode(1)
        decoder.popData(4)
        self.executionCode = decoder.intDecode(1)
        decoder.popData(2)
        lenNumOfTagsFound = decoder.lengthDecode()[0]
        self.numOfTagsFound = decoder.intDecode(lenNumOfTagsFound)
        if len(decoder.data) != 0:
            decoder.popData(2)
            lenTagIDs = decoder.lengthDecode()[0]
            while len(decoder.data) != 0:
                decoder.popData(2)
                lenTagID = decoder.lengthDecode()[0]
                self.tagIDs.append(decoder.data[:2 * lenTagID])
                decoder.popData(2 * lenTagID)
        
        return {'ComplicationCode':self.completionCode, 'ExecutionCode':self.executionCode, 'NumberOfTagsFound':self.numOfTagsFound, 'Identities':self.tagIDs}
        
    
if __name__ == '__main__':
    command = InventoryTagsCommand(1, 2,0, 1)
    print command.encode()